package com.syf.core.utils;

import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

public class BeanValidatorUtils {
    private static final ValidatorFactory validatorFactory = Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .failFast(false)
            .buildValidatorFactory();

    private static final Validator validator = validatorFactory.getValidator();

    public static <T> Set<ConstraintViolation<T>> validateBean(T bean, Class<T> beanClazz, Class<?>... groups) {
        Set<ConstraintViolation<T>> resultSet = validator.validate(bean, groups);
        return resultSet;
    }

    public static <T> String buildValidateMessage(Set<ConstraintViolation<T>> constraintViolations, Class<T> beanClazz){
        StringBuilder sb = new StringBuilder();
        for(ConstraintViolation constraintViolation:constraintViolations){
            sb.append("[")
                    .append(constraintViolation.getPropertyPath())
                    .append("-")
                    .append(constraintViolation.getMessage())
                    .append(":")
                    .append(constraintViolation.getInvalidValue())
                    .append("]");
        }

        if(sb.length() > 1024){
            return sb.substring(0, 1024);
        }
        return sb.toString();
    }
}
